package com.yz.jdd.module.scan.view;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;

import com.google.zxing.Result;
import com.yunzong.permissions.OnPermission;
import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yz.jdd.R;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.module.cashier.scanpay.ScanpayActivity;
import com.yz.jdd.scan.ScanEventListener;
import com.yz.jdd.scan.SoftwareScanner;
import com.yz.jdd.scan.view.ViewfinderView;
import com.yz.jdd.webview.H5BridgeActivity;
import com.yz.jdd.webview.H5BridgeOtherActivity;
import com.yz.jdd.webview.Router;
import com.yz.jdd.widget.PublicDialog;
import com.yz.jdd.widget.TopDialog;

import java.util.List;


/**
 * Created by cc on 2018/4/10.
 */

public class ScanActivity extends BaseActivity implements View.OnClickListener {


    TextView topBack;

    TextView topTitle;

    TextView topRight;

    SurfaceView previewView;

    ViewfinderView viewfinderView;

    private SoftwareScanner softwareScanner;


    private boolean isDecoded = true;//一次支付只能扫一次

    String from,title,text;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        isScan = true;
        super.onCreate(savedInstanceState);
       getCameraPermission();
    }


    private void getCameraPermission() {
        XXPermissions.with(ScanActivity.this)
                //.constantRequest() //可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                .permission(Permission.CAMERA
                ) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        LogUtils.e("=== noPermission: "+isAll);
                        dismissTopDialog();
                        //必要权限
                        if (granted.contains(Permission.CAMERA)) {
                            setContentView(R.layout.activity_scan);

                            from = getIntent().getStringExtra("from");
                            title= getIntent().getStringExtra("title");
                            Log.e("lkf",title);
                            text= getIntent().getStringExtra("text");
                            initView();


                            softwareScanner = SoftwareScanner.getInstance(ScanActivity.this);
                            softwareScanner.init(previewView, viewfinderView);
                            toScan(true);

                        } else {
                            permissionDialog();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        LogUtils.e("=== noPermission: "+quick);
                        dismissTopDialog();
                        if (quick) {
                            showToast("被永久拒绝授权，请手动授予权限");
                            if (denied.contains(Permission.CAMERA)) {
                                permissionDialog();
                            }
                        }else{
                            ScanActivity.this.finish();
                        }


                    }

                });
        if (!XXPermissions.isHasPermission(ScanActivity.this,Permission.CAMERA)){
            showTopDialog("为了您能正常使用【扫码支付】【设备绑定】功能，需向您申请相机权限。如果不允许，您将无法使用扫码功能。");
        }

    }

    //未授权权限弹出对话框
    public void permissionDialog() {
        final PublicDialog permission = new PublicDialog(ScanActivity.this);
        permission.setTitle("请开启相关权限");
        permission.setMessage("为保证扫码功能正常使用，请务必开启相机权限!");
        permission.setRightBtn("去设置", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                XXPermissions.gotoPermissionSettings(ScanActivity.this);
                permission.dismiss();
            }
        });
        permission.setLeftBtn("取消", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                permission.dismiss();
                ScanActivity.this.finish();
            }
        });
        permission.setCancelable(false);
        permission.show();

    }
    private TopDialog topDialog = null;

    public void showTopDialog(String content) {
        topDialog = new TopDialog(this);
        topDialog.setContent(content);
        topDialog.show();
    }

    private void dismissTopDialog() {
        if (topDialog != null) {
            topDialog.dismiss();
            topDialog = null;
        }

    }
    @Override
    protected void onStop() {
        super.onStop();
        stopScanner();
    }

    @Override
    protected void onResume() {
        super.onResume();
        toScan(true);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SoftwareScanner.getInstance(this).release();
    }

    void initView() {
        topBack = (TextView) findViewById(R.id.top_back);
        topBack.setVisibility(View.VISIBLE);
        topBack.setOnClickListener(this);
        topTitle = (TextView) findViewById(R.id.top_title);
        if(!TextUtils.isEmpty(title)){
            topTitle.setText(title);
        }else{
            topTitle.setText("扫一扫");
        }

        previewView = (SurfaceView) findViewById(R.id.preview_view);
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

        if(!TextUtils.isEmpty(text)){
            viewfinderView.setText(text);
        }

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.top_back) {
            if ("H5BridgeActivity".equals(from)) {
                Intent intent = new Intent(ScanActivity.this, H5BridgeActivity.class);
                intent.putExtra("code", "");
                intent.putExtra("cancel", "cancel");
                String sessionId= PreferencesUtils.getString(this, BaseConfigs.PREF_SESSIONID);
                intent.putExtra("sessionId",sessionId);
                setResult(5);
            } else if ("H5BridgeOtherActivity".equals(from)) {
                Intent intent = new Intent(ScanActivity.this, H5BridgeOtherActivity.class);
                intent.putExtra("cancel", "cancel");
                intent.putExtra("code", "");
                String sessionId=PreferencesUtils.getString(this, BaseConfigs.PREF_SESSIONID);
                intent.putExtra("sessionId",sessionId);
                setResult(5);
            }
            finish();
        }

    }

//    /**
//     * 【重新扫码】
//     */
//    public void restartScanner() {
//
//        if (softwareScanner!=null&&softwareScanner.getCaptureHandler() != null) {
//            softwareScanner.getCaptureHandler().sendEmptyMessage(R.id.restart_preview);
//        }
//    }

    /**
     * 停止扫码
     */
    public void stopScanner() {
        if (softwareScanner != null)
            softwareScanner.stopScan();
    }

    /**
     * UI线程初始化相机
     *
     * @param isScanable
     */
    private void toScan(final boolean isScanable) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (softwareScanner!=null){
                    softwareScanner.doScan(new ScanEventListener() {
                        @Override
                        public void onSuccess(Result result) {
                            Log.d("TAG", "onSuccess: asasasasasasasasasasasasasasasasaasasasasasasasasasasas");
                            if (result != null && isDecoded) {
                                Log.d("TAG", "onSuccess: qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
                                isDecoded = false;
//                                if ("H5BridgeActivity".equals(from)) {
//                                    Log.d("TAG", "onSuccess: wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww");
//                                    Intent intent = new Intent(ScanActivity.this, H5BridgeActivity.class);
//                                    intent.putExtra("code", result.getText());
//                                    String sessionId=PreferencesUtils.getString(ScanActivity.this, BaseConfigs.PREF_SESSIONID);
//                                    intent.putExtra("sessionId",sessionId);
//                                    setResult(5, intent);
//                                } else if ("H5BridgeOtherActivity".equals(from)) {
//                                    Log.d("TAG", "onSuccess: eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
//                                    Intent intent = new Intent(ScanActivity.this, H5BridgeOtherActivity.class);
//                                    intent.putExtra("code", result.getText());
//                                    String sessionId=PreferencesUtils.getString(ScanActivity.this, BaseConfigs.PREF_SESSIONID);
//                                    intent.putExtra("sessionId",sessionId);
//                                    setResult(5, intent);
//                                } else if("homeFragment".equals(from)){
//                                    Log.d("TAG", "onSuccess: rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
//                                    Router.startScanning(ScanActivity.this,result.getText());
//                                }
                                if ("H5Fragment".equals(from)) {
                                    LogUtils.d("--- from H5Fragment");
                                    Intent intent = new Intent();
                                    intent.putExtra("code", result.getText());
                                    String sessionId=PreferencesUtils.getString(ScanActivity.this, BaseConfigs.PREF_SESSIONID);
                                    intent.putExtra("sessionId",sessionId);
                                    setResult(5, intent);
                                }else if ("homeFragment".equals(from)){
                                    LogUtils.d("--- from homeFragment");
                                    Router.startScanning(ScanActivity.this,result.getText());
                                }
                                finish();
                            }
                        }

                        @Override
                        public void onError() {
                            Log.d("TAG", "onSuccess: sdsdsdsdsdsdsdsdsdsdssddsdsdsdsdsdsd");
//                            if ("H5BridgeActivity".equals(from)) {
//                                Intent intent = new Intent(ScanActivity.this, H5BridgeActivity.class);
//                                intent.putExtra("code", "");
//                                String sessionId=PreferencesUtils.getString(ScanActivity.this, BaseConfigs.PREF_SESSIONID);
//                                intent.putExtra("sessionId",sessionId);
//                                setResult(5, intent);
//                            } else if ("H5BridgeOtherActivity".equals(from)) {
//                                Intent intent = new Intent(ScanActivity.this, H5BridgeOtherActivity.class);
//                                intent.putExtra("code", "");
//                                String sessionId=PreferencesUtils.getString(ScanActivity.this, BaseConfigs.PREF_SESSIONID);
//                                intent.putExtra("sessionId",sessionId);
//                                setResult(5, intent);
//                            }
                            if ("H5Fragment".equals(from)) {
                                LogUtils.d("--- from H5Fragment error");
                                Intent intent = new Intent();
                                intent.putExtra("code", "");
                                String sessionId=PreferencesUtils.getString(ScanActivity.this, BaseConfigs.PREF_SESSIONID);
                                intent.putExtra("sessionId",sessionId);
                                setResult(5, intent);
                            }
                            finish();
                        }
                    }, isScanable);
                }

            }
        });

    }

}
